package net.goutalk.glcs.module.erpModel.caseErpMaterial.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.toolkit.MPJWrappers;
import net.goutalk.glcs.common.annotation.GlcsLog;
import net.goutalk.glcs.common.constant.GlobalConstant;
import net.goutalk.glcs.common.enums.YesOrNoEnum;
import net.goutalk.glcs.common.model.result.R;
import net.goutalk.glcs.common.page.ConventPage;
import net.goutalk.glcs.common.page.PageOutput;
import net.goutalk.glcs.common.utils.VoToColumnUtil;
import net.goutalk.glcs.module.erpModel.caseErpMaterial.dto.AddCaseErpMaterialClassesDto;
import net.goutalk.glcs.module.erpModel.caseErpMaterial.dto.CaseErpMaterialClassesPageDto;
import net.goutalk.glcs.module.erpModel.caseErpMaterial.dto.UpdateCaseErpMaterialClassesDto;
import net.goutalk.glcs.module.erpModel.caseErpMaterial.entity.CaseErpMaterialClasses;
import net.goutalk.glcs.module.erpModel.caseErpMaterial.service.ICaseErpMaterialClassesService;
import net.goutalk.glcs.module.erpModel.caseErpMaterial.vo.CaseErpMaterialClassesExportVo;
import net.goutalk.glcs.module.erpModel.caseErpMaterial.vo.CaseErpMaterialClassesVo;
import net.goutalk.glcs.module.organization.entity.User;
import net.goutalk.glcs.module.workflow.utils.WorkFlowUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 物料类别配置【case_erp_material_classes】 前端控制器
 * </p>
 *
 * @author hnyyzy
 * @since 2023-06-19
 */
@RestController
@RequestMapping(GlobalConstant.CASE_ERP_MATERIAL +"/caseErpMaterialClasses")
@Api(value = GlobalConstant.CASE_ERP_MATERIAL +"/caseErpMaterialClasses", tags = "物料类别配置")
@AllArgsConstructor
public class CaseErpMaterialClassesController {
    private ICaseErpMaterialClassesService caseErpMaterialClassesService;

    @GetMapping(value = "/list")
    @ApiOperation("物料类别列表")
    public R list() {
        List<CaseErpMaterialClasses> list = caseErpMaterialClassesService.list(Wrappers.<CaseErpMaterialClasses>query().lambda().eq(CaseErpMaterialClasses::getState, YesOrNoEnum.YES.getCode()));
        return R.ok(list);
    }

    @GetMapping(value = "/page")
    @ApiOperation("物料类别配置列表分页")
    public R page(CaseErpMaterialClassesPageDto dto) {
        if (ObjectUtil.isNotNull(dto.getStartTime()) && ObjectUtil.isNotNull(dto.getEndTime())) {
            dto.setStartTime(WorkFlowUtil.getStartOfDay(dto.getStartTime()));
            dto.setEndTime(WorkFlowUtil.getEndOfDay(dto.getEndTime()));
        }
        IPage<CaseErpMaterialClassesVo> page = caseErpMaterialClassesService.selectJoinListPage(ConventPage.getPage(dto), CaseErpMaterialClassesVo.class,
                MPJWrappers.<CaseErpMaterialClasses>lambdaJoin()
                        .distinct()
                        .orderByDesc(CaseErpMaterialClasses::getCreateDate)
                        .like(StrUtil.isNotBlank(dto.getTypeName()), CaseErpMaterialClasses::getTypeName, dto.getTypeName())
                        .between(ObjectUtil.isNotNull(dto.getStartTime()) && ObjectUtil.isNotNull(dto.getEndTime())
                                , CaseErpMaterialClasses::getCreateDate, dto.getStartTime(), dto.getEndTime())
                        .selectAs(User::getName, CaseErpMaterialClassesVo::getCreateUserName)
                        .select(CaseErpMaterialClasses::getId)
                        .select(CaseErpMaterialClasses.class, x -> VoToColumnUtil.fieldsToColumns(CaseErpMaterialClassesVo.class).contains(x.getProperty()))
                        .leftJoin(User.class, User::getId, CaseErpMaterialClasses::getCreateUserId));

        PageOutput<CaseErpMaterialClassesVo> pageOutput = ConventPage.getPageOutput(page);
        return R.ok(pageOutput);
    }


    @GetMapping(value = "/info")
    @ApiOperation(value = "根据id查询物料类别配置信息")
    public R info(@RequestParam Long id) {
        CaseErpMaterialClasses caseErpMaterialClasses = caseErpMaterialClassesService.getById(id);
        if (caseErpMaterialClasses == null) {
            R.error("找不到此物料类别配置！");
        }
        return R.ok(BeanUtil.toBean(caseErpMaterialClasses, CaseErpMaterialClassesVo.class));
    }

    @PostMapping
    @ApiOperation(value = "新增物料类别配置")
    public R add(@Valid @RequestBody AddCaseErpMaterialClassesDto dto) {
        long count = caseErpMaterialClassesService.count(Wrappers.<CaseErpMaterialClasses>query().lambda().eq(CaseErpMaterialClasses::getTypeName, dto.getTypeName()));
        if (count > 0) {
            return R.error("此物料类别已经存在！");
        }
        CaseErpMaterialClasses  caseErpMaterialClasses= BeanUtil.toBean(dto, CaseErpMaterialClasses.class);
        caseErpMaterialClassesService.save(caseErpMaterialClasses);
        return R.ok(true);
    }

    @PutMapping
    @ApiOperation(value = "修改物料类别配置")
    public R update(@Valid @RequestBody UpdateCaseErpMaterialClassesDto dto) {
        CaseErpMaterialClasses caseErpMaterialClasses = BeanUtil.toBean(dto, CaseErpMaterialClasses.class);
        caseErpMaterialClassesService.updateById(caseErpMaterialClasses);
        return R.ok(true);
    }

    @DeleteMapping
    @ApiOperation(value = "删除")
    @GlcsLog(value = "删除物料类别配置")
    public R delete(@Valid @RequestBody Long id) {
        return R.ok(caseErpMaterialClassesService.removeById(id));
    }

    @PostMapping(value = "/export")
    @ApiOperation(value = "导出")
    @GlcsLog(value = "导出表单数据")
    public ResponseEntity<byte[]> export(@Valid @RequestBody List<Long> ids) {
        List<CaseErpMaterialClassesExportVo> caseErpMaterialClassesExportVoList= caseErpMaterialClassesService.selectJoinList(CaseErpMaterialClassesExportVo.class,
                MPJWrappers.<CaseErpMaterialClasses>lambdaJoin()
                        .distinct()
                        .in(CaseErpMaterialClasses::getId, ids)
                        .selectAs(User::getName, CaseErpMaterialClassesExportVo::getCreateUserName)
                        .select(CaseErpMaterialClasses::getId)
                        .select(CaseErpMaterialClasses.class, x -> VoToColumnUtil.fieldsToColumns(CaseErpMaterialClassesExportVo.class).contains(x.getProperty()))
                        .leftJoin(User.class, User::getId, CaseErpMaterialClasses::getCreateUserId));
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        EasyExcel.write(bot, CaseErpMaterialClassesExportVo.class).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(caseErpMaterialClassesExportVoList);
        return R.fileStream(bot.toByteArray(), "物料类别配置" + ExcelTypeEnum.XLSX.getValue());
    }

    @PostMapping("/import")
    @ApiOperation(value = "导入")
    public R importData(@RequestParam MultipartFile file) throws IOException {
        List<AddCaseErpMaterialClassesDto> savedDataList = EasyExcel.read(file.getInputStream()).head(AddCaseErpMaterialClassesDto.class).sheet().doReadSync();
        caseErpMaterialClassesService.saveBatch(BeanUtil.copyToList(savedDataList, CaseErpMaterialClasses.class));
        return R.ok(true);
    }

    @GetMapping("/export")
    @ApiOperation(value = "下载模板")
    @SneakyThrows
    public ResponseEntity<byte[]> export() {
        List<AddCaseErpMaterialClassesDto> caseErpMaterialClassesList = new ArrayList<>();
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        EasyExcel.write(bot, AddCaseErpMaterialClassesDto.class).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(BeanUtil.copyToList(caseErpMaterialClassesList, AddCaseErpMaterialClassesDto.class));
        return R.fileStream(bot.toByteArray(), "物料类别配置模板" + ExcelTypeEnum.XLSX.getValue());
    }

}
